package com.example.demo.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.xdevapi.JsonArray;
import com.mysql.cj.xdevapi.JsonValue;
import org.springframework.web.bind.annotation.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;

@RestController
public class PostController {

    public JSONObject getPostDetail(@RequestParam JSONObject frontJson){
        JSONObject json=new JSONObject();
        return json;
    }

    public JSONObject createPost(@RequestParam JSONObject frontJson){
        JSONObject json=new JSONObject();
        return json;
    }

    public JSONObject deletePost(@RequestParam JSONObject frontJson){
        JSONObject json=new JSONObject();
        return json;
    }

    public JSONObject highlightPost(@RequestParam JSONObject frontJson){
        JSONObject json=new JSONObject();
        return json;
    }

    @PostMapping("/createComment")//url: 'http://localhost:8080/post/createComment'
    public JSONObject createComment(@RequestBody JSONObject frontJson){
        JSONObject json=new JSONObject();
        JSONArray arrayPlayer = new JSONArray();
        JSONObject json1 = new JSONObject();
        SQLController sqlController=new SQLController();
        Connection connection=sqlController.ConnectToSql("jdbc:mysql://localhost:3306/jidazhidemai","root","gFL123456"+"");

        if(connection!=null){
            int postid=frontJson.getInteger("postid");
            String wxid=frontJson.getString("wxid");
            String content= frontJson.getString("content");

            try {
                String sql1 = "select count(*) from post where postid=" + postid + " limit 1";
                PreparedStatement ps = connection.prepareStatement(sql1);
                ResultSet Judge = ps.executeQuery();
                int ct = 0;
                while (Judge.next()) {
                    ct = postid;
                    System.out.println(ct);
                }
                if (ct == 0) {
                    System.out.println("该帖子不存在");
                    json.put("status", "FALL_NOMATCH");
                } else {
                    System.out.println("该帖子存在");
                    //更新post表中该post的comments字段(comments字段为text,string;以下划线_分割）
                    String sql2 = "select * from `post` where postid=" + postid;
                    Statement stmt2 = connection.createStatement();
                    ResultSet rs2 = stmt2.executeQuery(sql2);
                    String postOldComments = null;
                    String postNewComments = null;
                    String userOldComments = null;
                    String userNewComments = null;

                    while (rs2.next()) {
                        arrayPlayer =  JSONArray.parseArray(rs2.getString("comments"));
                        int n;
                        if(arrayPlayer==null){
                            n=0;
                            arrayPlayer = new JSONArray();
                        }
                        else n=arrayPlayer.size();
                        json1.put("commentid",n);
                        json1.put("poster",wxid);
                        json1.put("content",content);
                        arrayPlayer.add(json1);

                    }
                    String sql3 = "update post set `comments`=?,`comments_longth`=? where postid=?";
                    PreparedStatement stmt3 = connection.prepareStatement(sql3);
                    stmt3.setString(1, String.valueOf(arrayPlayer));
                    stmt3.setInt(2,arrayPlayer.size());
                    stmt3.setInt(3,postid);
                    stmt3.executeUpdate();

                    stmt3.close();

                    //给该用户的comments字段插入该postid和commentid
                    String sql4 = "select comments from `user` where wxid=?";
                    PreparedStatement stmt4 = connection.prepareStatement(sql4);
                    stmt4.setString(1, wxid);
                    ResultSet rs4 = stmt4.executeQuery();
                    JSONObject json2 = new JSONObject();
                    while (rs4.next()) {

                        arrayPlayer = JSONArray.parseArray(rs4.getString("comments"));
                        json2.put("poster",wxid);
                        int n;
                        if(arrayPlayer==null){
                            n=0;
                            arrayPlayer = new JSONArray();
                        }
                        else n=arrayPlayer.size();
                        json2.put("commentid",n);
                        arrayPlayer.add(json2);
                    }
                    rs4.close();
                    String sql5 = "update `user` set `comments`=? where wxid=?";
                    PreparedStatement stmt5 = connection.prepareStatement(sql5);
                    stmt5.setString(1, String.valueOf(arrayPlayer));
                    stmt5.setString(2,wxid);
                    stmt5.executeUpdate();
                    stmt5.close();

                    connection.close();
                    json.put("status", "COMPLETE");
                    json.put("postid", postid);
                    json.put("commentid", arrayPlayer.size());
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return json;
    }

    @PostMapping("/createVote")//url: 'http://localhost:8080/post/createVote'
    public JSONObject createVote(@RequestBody JSONObject frontJson){
        System.out.println(frontJson);
        JSONObject json=new JSONObject();
        SQLController sqlController=new SQLController();
        Connection connection=sqlController.ConnectToSql("jdbc:mysql://localhost:3306/jidazhidemai","root","gFL123456"+"");

        if(connection!=null){
            int postid=frontJson.getInteger("postid");
            String wxid=frontJson.getString("wxid");
            int vote=frontJson.getInteger("vote");

            try {
                String sql1 = "select count(*) from `post` where postid=? limit 1";
                PreparedStatement ps = connection.prepareStatement(sql1);
                ps.setString(1, String.valueOf(postid));
                ResultSet Judge = ps.executeQuery();
                int ct = 0;
                while (Judge.next()) {
                    ct = postid;
                    System.out.println(ct);
                }
                if(ct == 0)
                {
                    System.out.println("该帖子不存在");
                    json.put("status","FAIL_NOMATCH");
                }
                else
                {
                    int times=0;
                    System.out.println("该帖子存在");
                    //给该帖子点赞或点踩:post.like++或post.dislike++
                    //给该用户的votes字段插入该postid和vote;形式{postid: 5654, vote: 1}
                    String sql4="select votes from `user` where wxid=?";
                    PreparedStatement stmt4 = connection.prepareStatement(sql4);
                    stmt4.setString(1, wxid);
                    ResultSet rs4 = stmt4.executeQuery();
                    String userOldVotes=null;
                    String userNewVotes=null;
                    while (rs4.next()){
                        userOldVotes=rs4.getString("votes");
                        if(userOldVotes==null){
                            userNewVotes="{postid:"+postid+",vote:"+vote+"}_";
                            break;
                        }
                        List<String> postIds =new ArrayList<>();
                        postIds= new ArrayList<String>(Arrays.asList(userOldVotes.split("_")));
                        if(postIds.contains("{postid:"+postid+",vote:"+vote+"}")){
                            postIds=remove13(postIds, "{postid:"+postid+",vote:"+vote+"}");
                            userNewVotes=String.join("_",postIds)+"_";
                            times=1;
                        }
                        else if(postIds.contains("{postid:"+postid+",vote:"+(-vote)+"}")){
                            postIds=remove13(postIds, "{postid:"+postid+",vote:"+(-vote)+"}");
                            userNewVotes=String.join("_",postIds)+"_";
                            userNewVotes=userNewVotes+"{postid:"+postid+",vote:"+vote+"}_";
                            times=2;
                        }else
                            userNewVotes=userOldVotes+"{postid:"+postid+",vote:"+vote+"}_";
                    }
                    String sql5="update `user` set votes=? where wxid=?";
                    PreparedStatement stmt5 = connection.prepareStatement(sql5);
                    stmt5.setString(1, userNewVotes);
                    stmt5.setString(2, wxid);
                    stmt5.executeUpdate();
                    stmt5.close();

                    int oldLike = 0;
                    int oldDislike=0;
                    String sql2="select * from `post` where postid=?";
                    PreparedStatement stmt2 = connection.prepareStatement(sql2);
                    stmt2.setInt(1, postid);
                    ResultSet rs2 = stmt2.executeQuery();
                    while (rs2.next()){
                        oldLike= rs2.getInt("like");
                        oldDislike= rs2.getInt("dislike");
                    }
                    String sql31=null;
                    String sql32=null;
                    if(vote==1){
                        if(times==0){
                            oldLike=oldLike+1;
                        }else if(times==1){
                            oldLike=oldLike-1;
                        }else {
                            oldLike=oldLike+1;
                            oldDislike=oldDislike-1;
                        }
                    }else {
                        if(times==0){
                            oldDislike=oldDislike+1;
                        }else if(times==1){
                            oldDislike=oldDislike-1;
                        }else {
                            oldDislike=oldDislike+1;
                            oldLike=oldLike-1;
                        }
                    }
                    sql31="update post set `like`=? where postid=?";
                    PreparedStatement stmt31 = connection.prepareStatement(sql31);
                    stmt31.setInt(1, oldLike);
                    stmt31.setInt(2, postid);
                    stmt31.executeUpdate();
                    stmt31.close();

                    sql32="update post set `dislike`=? where postid=?";
                    PreparedStatement stmt32 = connection.prepareStatement(sql32);
                    stmt32.setInt(1, oldDislike);
                    stmt32.setInt(2, postid);
                    stmt32.executeUpdate();
                    stmt32.close();

                    connection.close();
                    json.put("status","COMPLETE");
                    json.put("postid",postid);
                    json.put("vote",vote);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return json;
    }
    public static List<String> remove13(List<String> list, String target){
        int size = list.size();
        for(int i = size - 1; i >= 0; i--){
            String item = list.get(i);
            if(target.equals(item)){
                list.remove(item);
            }
        }
        return list;
    }

}




